<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#example').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>
<?php
@set_time_limit(0);
function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}
function geofenceChk($date_offline,$deviceIMEI)
{
	$path1=DATAPATH.date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	//$path1="http://localhost/src/352848025673738_1.txt";
	if(chk_folder($path1))
	{
		$file1 = @fopen($path1, "r");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			  $data1= fgets($file1);				 
			}
			$data1 = getSortedData($data1);
			fclose($file1);
		}
		return $data1;
	}
		
}

$tmpId = -1;
$lat_lngArr = array();
$end = 1;
$geoId =  array();

function geoAlrtPerDay($lData,$geofenceType)
{ 
	$cnt = 0;
	$data1=explode("#",$lData);
	$timeArr= array();
	$strTime='';
	$endTime='';
	for($j1=0;$j1<count($data1);$j1++)
	{
		$data2=explode("@",$data1[$j1]);
		
		if(count($data2)>1)
		{
			$data3=explode(",",$data2[1]);
			$geodate = $data3[8];
			$geoTime = $data3[9];
			//echo "<br>";
			
			$pos1=calLat($data3[2]);
			$pos2=calLong($data3[1]);
			
			if($pos1>0 && $pos2>0)
			{
				
				if(!in_array($geoTime,$timeArr))
				{
					//$getDevice = "SELECT * FROM tb_geofence_info WHERE tgi_clientId = ".$_SESSION[clientID]." AND tgi_isActive = 1 ORDER BY tgi_id ASC";
					$getDevice = "SELECT * FROM tb_geofence_info WHERE tgi_clientId = ".$_SESSION[clientID]." AND tgi_isActive = 1 AND tgi_id  =  ".$geofenceType." ORDER BY tgi_id ASC";
					$resDevice = mysql_query($getDevice);
									
					if(@mysql_affected_rows() > 0)
					{
						
						$fetDevice = @mysql_fetch_assoc($resDevice);
						
							if($fetDevice[tgi_geoType] == "CIRCLE")
							{
								$lat_lng = explode(",",$fetDevice[tgi_latLong]);		
								$radius = $fetDevice[tgi_radius];
								//echo $lat_lng[0]." , ".$lat_lng[1]." , ".$radius." , ".$pos1." , ".$pos2."<br>";
								$latlngArr = drawCircle($lat_lng[0],$lat_lng[1],$radius);							
								
							}
							elseif($fetDevice[tgi_geoType] == "POLYGON")
							{
								$ltln1 = explode("#",$fetDevice[tgi_polyCoordinates]);
								for($k = 0 ;$k < count($ltln1)-1; $k++)
								{								
									$latlngArr[] = $ltln1[$k];										
								}
								//echo $pos1.','.$pos2." ".$fetDevice[tgi_name]."<br>";
								//echo "<br><br>";
							}
							$res = getGeofenceStatus($latlngArr,$pos1,$pos2);
							if($res == 1  && $strTime=='')
							{
								$strTime = date("h:i:s A",strtotime($geoTime));
								
							}
							elseif($res == 0 && $endTime=='' && $strTime!='')
							{
								$endTime = date("h:i:s A",strtotime($geoTime));
								$finaTime[] = $strTime.",".$fetDevice[tgi_name].",".$endTime.",".gmdate("H:i:s",(strtotime($endTime) - strtotime($strTime)));								
								$strTime='';
								$endTime='';
							}
							//$res = -1;
							$latlngArr = '';
					}
					array_push($timeArr,$geoTime);
				}
				
			}
		}
		
	}
	//echo $strTime;
	if($strTime != "" && $endTime == "")
	{
		$finaTime[] = $strTime.",".$fetDevice[tgi_name].",".$geoTime.",".gmdate("H:i:s",(strtotime($geoTime) - strtotime($strTime)));		
		//$finaTime[] = $strTime.",".$fetDevice[tgi_name].",---,---";		
	}
	//print_r($finaTime);
	//exit;
	if(count($finaTime)>0)
	{
		$finaTime = implode("@",$finaTime);
		return $finaTime;
	}
	else return false;
}

if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);
?>
<script type="text/javascript" language="javascript">


function validateMapReport()
{
   if(document.getElementById('selGeofenceId').value== 0 )
  { alert("Select Geofence");  document.getElementById('selGeofenceId').focus();  return 0;  }
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  

	
	return 1;
	
}
function sendCSVData()
{
  document.frmTripData.submit();
}

function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}

$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final">
<tr>
  <th colspan="5">Geofence Report</th></tr>
  <tr>    
    <td align="right"><span class="form_text">Select Geofence</span></td>
    <td align="left">
        <select name="selGeofenceId" id="selGeofenceId" tabindex="5" style="width:80%" >
        <option value="0">Select Geofence</option>
         <?php 
		$getGeofence =  "SELECT * FROM tb_geofence_info WHERE tgi_isActive = 1 AND tgi_clientId =".$_SESSION[clientID]." ORDER BY tgi_name ASC";
		$resGeofence = mysql_query($getGeofence);
		while($fetGeofence = @mysql_fetch_assoc($resGeofence)) 
		{ 
			if($_POST[selGeofenceId] == $fetGeofence[tgi_id])
				$select = 'selected="selected"';				
			else $select ='';
        ?>
        <option value="<?php echo $fetGeofence[tgi_id];?>" <?php echo $select ?>><?php echo $fetGeofence[tgi_name]; ?></option>
        <?php } ?>		
        </select>
    </td>
     <td align="right"><span class="form_text">Date</span></td>
    <td align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" size="12" tabindex="3" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/>&nbsp;
    </td>
    <td style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="7"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=geofence';" tabindex="8" /> 
</td>
  </tr>
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	
	
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{ 
//print_r($_POST);
?>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">   
 <thead>
      <tr>
        <th width="5%" >#</th>
        <th width="10%">Date</th>
        <th width="25%">Zone Name</th>
        <th width="18%">Device Name</th>
        <th width="12%">In Time (HH:MM:SS) </th>
        <th width="12%">Out Time (HH:MM:SS)</th>
        <th width="12%">Duration (HH:MM:SS)</th>
      </tr>
  </thead>
  <tbody>
<?php
$devArr = array();
if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);
while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
{
	$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
	//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
	if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
	{
		if($devices_fetch[di_deviceName])
		$devName = $devices_fetch[di_deviceName];
		else
		$devName = $devices_fetch[di_deviceId];
		
		$devArr[] = $devName;
		$data =  geofenceChk($_POST[from_date],$devices_fetch[di_imeiId]);
		$finData[$devName] = geoAlrtPerDay($data,$_POST[selGeofenceId]);		
	}
}
//print_r($finData);

$i = 0;
if(count($devArr)>0)
{			
	for($x=0; $x<count($devArr); $x++)
	{
		if($finData[$devArr[$x]] != "")
		{
		$finData1 = explode("@",$finData[$devArr[$x]]);
		//print_r($finData1);
		for($y=0; $y<count($finData1); $y++)
		{
			$splitData = explode(",",$finData1[$y]);
			
	?>	  
			<tr <?php if($i % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
				<td valign="top"><?php echo $i+1; ?></td>
				<td valign="top"><?php echo $_POST[from_date]; ?></td>
                <td valign="top"><?php echo ucfirst($splitData[1]); ?></td>
				<td valign="top"><?php echo ucfirst($devArr[$x]); ?></td>
				<td valign="top"><?php echo $splitData[0]; ?></td>
				<td valign="top"><?php echo $splitData[2]; ?></td>
                <td valign="top"><?php echo $splitData[3]; ?></td>
			</tr>
	<?php      
		   $i++; 			
		}
		}
   }

} ///end of if(file exists)
?>	  
</tbody>
</table>	
<?php
  
}///end of post

?>
